﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Fujitsu.JiraAnalysis.DAL;

namespace Fujitsu.JiraAnalysis.UI
{
    public partial class Configuration : System.Web.UI.Page
    {
        private ProjectStorage projectStorage = new ProjectStorage();

        protected void gridViewProjects_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType != DataControlRowType.DataRow)
                return;
            var project = e.Row.DataItem as Project;
            if (project != null)
            {
                if (project.IsNeedCheck)
                    e.Row.Cells[2].ForeColor = System.Drawing.Color.Red;
                var deleteButton = e.Row.FindControl("btnDeleteProject") as ImageButton;
                if (deleteButton != null)
                {
                    var message = string.Format("Are you sure you want to delete project configuration for \'{0}\'?", project.Name);
                    deleteButton.Attributes.Add("onclick", string.Format("return confirmProjectDelete(\"{0}\");", message));
                }
            }
        }

        protected void ProjectsDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)
        {
            var returnValue = e.ReturnValue as List<Project>;
            errorNoProjects.Visible = returnValue.Count == 0;
            gridViewProjects.Visible = !errorNoProjects.Visible;
            errorProjectDelete.Visible = false;
        }

        protected void gridViewProjects_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "deleteProject")
            {
                var projectId = int.Parse(e.CommandArgument.ToString());
                try
                {
                    projectStorage.DeleteProject(projectId);
                    gridViewProjects.DataBind();
                    errorProjectDelete.Visible = false;
                }
                catch(Exception)
                {
                    errorProjectDelete.Visible = true;
                }
            }
        }
    }
}